package com.kk.license.common;

import com.kk.license.common.bean.CustomKeyStoreParam;
import com.kk.license.common.bean.LicenseCheckModel;
import com.kk.license.common.bean.LicenseVerifyParam;
import de.schlichtherle.license.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * @author wangkang
 * @version 1.0
 * @description License校验类
 * @create 2023-07-17 10:17
 */

public class LicenseVerify {
    public static Logger log = LoggerFactory.getLogger(LicenseVerify.class);

    /**
     * 安装License证书
     */
    public synchronized LicenseContent install(LicenseVerifyParam param) {
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //1. 安装证书
        try {
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();

            result = licenseManager.install(new File(param.getLicensePath()));
            log.info(MessageFormat.format("证书安装成功，证书有效期：{0} - {1}", format.format(result.getNotBefore()), format.format(result.getNotAfter())));
        } catch (FileNotFoundException e) {
            log.error("证书安装失败{}文件不存在", param.getLicensePath());
        }catch (BadPaddingException e){
            log.error("证书安装失败！公钥密码不一致");
        }catch (Exception e) {
            log.error("证书安装失败！", e);
        }

        return result;
    }

    /**
     * 校验License证书
     *
     * @return boolean
     */
    public boolean verify() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //校验证书
        try {
            LicenseContent licenseContent = licenseManager.verify();

            log.info(MessageFormat.format("证书校验通过，证书有效期：{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));
            return true;
        } catch (NoLicenseInstalledException e) {
            log.error("证书校验失败！证书未安装");
            return false;
        } catch (Exception e) {
            log.error("证书校验失败！", e);
            return false;
        }
    }

    /**
     * 获取license授权的通道数
     * @return
     */
    public Integer getChannels() {
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        try {
            LicenseContent licenseContent = licenseManager.verify();

            LicenseCheckModel licenseCheckModel = (LicenseCheckModel)licenseContent.getExtra();
            return licenseCheckModel.getAllowChannel();
        } catch (Exception e) {
            log.error("证书校验失败！", e);
            return -1;
        }

    }

    /**
     * 初始化证书生成参数
     *
     * @param param License校验类需要的参数
     * @return de.schlichtherle.license.LicenseParam
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param) {
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());

        KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class
                , param.getPublicKeysStorePath()
                , param.getPublicAlias()
                , param.getStorePass()
                , null);

        return new DefaultLicenseParam(param.getSubject()
                , preferences
                , publicStoreParam
                , cipherParam);
    }

}
